package com.czk.dbcpconnectionpool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取jdbc连接
 * @Author ChenZhangKun
 * @Date 2020/9/15 9:33
 */
public class JDBCUtils {
    private static List<Connection> list=new ArrayList<>(10);
    // 注册驱动
    static {
        try {
            // 注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 获取连接池
            for (int i = 0; i < 5; i++) {
                Connection connection= DriverManager.getConnection("jdbc:mysql://192.168.89.146:6665/activiti","root","123456");
                list.add(connection);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     */
    public static Connection getConnection(){
        if (list.size()==0){
            for (int i = 0; i < 5; i++) {
                try {
                    Connection connection=DriverManager.getConnection("jdbc:mysql://192.168.89.146:6665/activiti","root","123456");
                    list.add(connection);
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
        Connection connection=list.remove(0);
        // 获取连接成功
        if (connection!=null){
            System.out.println("获取连接成功，还有"+list.size()+"个连接");
        }
        return connection;
    }

    /**
     * 归还连接
     */
    public static void backConnection(Connection connection){
        if (list!=null){
            list.add(connection);
            System.out.println("还有"+list.size()+"个连接");
        }else {
            // 归还连接失败
            System.out.println("归还连接失败");
        }

    }
}
